package com.example.choupaiapp.main.fragment.message;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.choupaiapp.R;
import com.example.choupaiapp.common.adapter.BaseAdapterHelper;
import com.example.choupaiapp.common.adapter.QuickAdapter;
import com.example.choupaiapp.common.constant.Contacts;
import com.example.choupaiapp.common.finalokgo.callback.Callback;
import com.example.choupaiapp.common.finalokgo.request.RequestType;
import com.example.choupaiapp.common.ui.fragment.CommonFragment;
import com.example.choupaiapp.common.util.ContextUtil;
import com.example.choupaiapp.common.util.DialogUtil;
import com.example.choupaiapp.common.util.SharedPreferencesHelp;
import com.example.choupaiapp.common.util.Utils;
import com.example.choupaiapp.common.view.XListView;
import com.example.choupaiapp.main.activity.find.FindDetailActivity;
import com.example.choupaiapp.main.activity.find.FindVideoDetailActivity;
import com.example.choupaiapp.main.activity.home.OtherInfoActivity;
import com.example.choupaiapp.main.activity.message.ByIdDetailActivity;
import com.example.choupaiapp.main.activity.message.PraiseCommentFollowActivity;
import com.example.choupaiapp.main.bean.FindDetailBean;
import com.example.choupaiapp.main.bean.MessageRemindBean;
import com.example.choupaiapp.main.bean.UserInfoBean;
import com.example.choupaiapp.main.bean.VideoListBean;
import com.example.choupaiapp.main.constant.Config;
import com.example.choupaiapp.main.constant.Url;
import com.example.choupaiapp.main.bean.SendCodeBean;
import com.gcssloop.widget.RCImageView;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.mcxtzhang.swipemenulib.SwipeMenuLayout;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by ASUS on 2019/11/6.
 */

public class RemindFragment extends CommonFragment implements OnRefreshLoadMoreListener {

    Unbinder unbinder;
    @BindView(R.id.mark_ll)
    LinearLayout markLl;
    @BindView(R.id.praise_num)
    TextView praiseNum;
    @BindView(R.id.comment_num)
    TextView commentNum;
    @BindView(R.id.follow_num)
    TextView followNum;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.listview)
    XListView listview;
    private int pageNum = 1;
    private int pageSize = 20;
    private QuickAdapter<MessageRemindBean.PageBean.ListBean> quickAdapter;
    private UserInfoBean mUserInfoBean;

    public static RemindFragment newInstance() {
        return new RemindFragment();
    }

    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_remind, container, false);
        unbinder = ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        refreshLayout.setOnRefreshLoadMoreListener(this);
        refreshLayout.setRefreshHeader(new MaterialHeader(context).setColorSchemeResources(R.color.common_color));

        mUserInfoBean = (UserInfoBean) SharedPreferencesHelp.getBean("userInfo");

        quickAdapter = new QuickAdapter<MessageRemindBean.PageBean.ListBean>(context, R.layout.item_remind_child) {
            @Override
            protected void convert(BaseAdapterHelper helper, MessageRemindBean.PageBean.ListBean item) {
                SwipeMenuLayout swipemenulayout = helper.getView(R.id.swipemenulayout);
                Button delete = helper.getView(R.id.delete);
                delete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (Utils.isDoubleClick()) {
                            return;
                        }
                        showDialog(context, "删除中...");
                        swipemenulayout.quickClose();
                        HttpParams params = new HttpParams();
                        params.put("id", item.getId());
                        finalOkGo.requestHead(RequestType.POSTHEAD, Url.DELETE_REMIND_MESSAGE, params, Url.DELETE_REMIND_MESSAGE, new Callback<SendCodeBean>() {
                            @Override
                            public void onSuccess(SendCodeBean sendCodeBean) {
                                dismissDialog();
                                if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                                    quickAdapter.remove(helper.getPosition());
                                    notifyDataSetChanged();
                                } else {
                                    if (sendCodeBean.getCode() == Contacts.TOKEN_EMPTY) {
                                    } else {
                                        showImageToas(sendCodeBean.getMsg());
                                    }
                                }
                            }

                            @Override
                            public void onError(Response response) {
                                super.onError(response);
                                dismissDialog();
                            }
                        });

                    }
                });

                helper.setText(R.id.description, "提到了你");
                helper.setText(R.id.name, item.getNickname());

                CircleImageView head_photo = helper.getView(R.id.head_photo);
                RCImageView photo = helper.getView(R.id.photo);
//                TextView follow = helper.getView(R.id.follow);
                RelativeLayout photo_rl = helper.getView(R.id.photo_rl);
                RelativeLayout follow_rl = helper.getView(R.id.follow_rl);
                View follow_tip = helper.getView(R.id.follow_tip);
                View photo_tip = helper.getView(R.id.photo_tip);

                photo_rl.setVisibility(View.VISIBLE);
                follow_rl.setVisibility(View.GONE);
                photo.setVisibility(View.VISIBLE);
                photo_tip.setVisibility(View.INVISIBLE);

                if (item.getStatus() == 0) {
                    follow_tip.setVisibility(View.VISIBLE);
                } else {
                    follow_tip.setVisibility(View.INVISIBLE);
                }

                if (item.getModule() == 1) {
                    if (item.getContentType() == 1) {
                        photo.setVisibility(View.VISIBLE);
                        Glide.with(context)
                                .load(item.getImage() + "?vframe/jpg/offset/1")
                                .dontAnimate()
                                .placeholder(R.color.color_f3f3)
                                .centerCrop()
                                .into(photo);
                    } else if (item.getContentType() == 2) {
                        photo.setVisibility(View.VISIBLE);
                        Glide.with(context)
                                .load(item.getImage().split("\\|")[0] + Config.IMAGE_LIM)
                                .dontAnimate()
                                .placeholder(R.color.color_f3f3)
                                .centerCrop()
                                .into(photo);
                    } else if (item.getContentType() == 3) {
                        photo.setVisibility(View.INVISIBLE);
                    }
                } else if (item.getModule() == 2) {
                    if (item.getContentType() == 1) {
                        photo.setVisibility(View.VISIBLE);
                        Glide.with(context)
                                .load(item.getImage().split("\\|")[0] + Config.IMAGE_LIM)
                                .dontAnimate()
                                .placeholder(R.color.color_f3f3)
                                .centerCrop()
                                .into(photo);
                    } else if (item.getContentType() == 2) {
                        photo.setVisibility(View.VISIBLE);
                        Glide.with(context)
                                .load(item.getImage() + "?vframe/jpg/offset/1")
                                .dontAnimate()
                                .placeholder(R.color.color_f3f3)
                                .centerCrop()
                                .into(photo);
                    } else if (item.getContentType() == 3) {
                        photo.setVisibility(View.INVISIBLE);
                    }
                }

                if (item.getByUserId() == item.getAuthorId()) {
                    if (item.getAnonymity() == 1) {
                        helper.setText(R.id.name, "匿名用户");
                        Glide.with(context)
                                .load("")
                                .dontAnimate()
                                .error(R.mipmap.head_anonymous_orange)
                                .into(head_photo);

                        head_photo.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                if (Utils.isDoubleClick()) {
                                    return;
                                }
                                item.setStatus(1);
                                quickAdapter.notifyDataSetChanged();
                            }
                        });
                    } else {
                        helper.setText(R.id.name, item.getNickname());
                        Glide.with(context)
                                .load(item.getAvatar() + Config.IMAGE_LIM)
                                .dontAnimate()
                                .placeholder(R.mipmap.icon_no_head)
                                .into(head_photo);

                        head_photo.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                if (Utils.isDoubleClick()) {
                                    return;
                                }
                                Bundle bundle1 = new Bundle();
                                bundle1.putString("userId", item.getByUserId() + "");
                                bundle1.putString("userName", item.getNickname());
                                startActivity(OtherInfoActivity.class, bundle1);
                                item.setStatus(1);
                                quickAdapter.notifyDataSetChanged();
                            }
                        });
                    }
                } else {
                    helper.setText(R.id.name, item.getNickname());
                    Glide.with(context)
                            .load(item.getAvatar() + Config.IMAGE_LIM)
                            .dontAnimate()
                            .placeholder(R.mipmap.icon_no_head)
                            .into(head_photo);

                    head_photo.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            if (Utils.isDoubleClick()) {
                                return;
                            }
                            Bundle bundle1 = new Bundle();
                            bundle1.putString("userId", item.getByUserId() + "");
                            bundle1.putString("userName", item.getNickname());
                            startActivity(OtherInfoActivity.class, bundle1);
                            item.setStatus(1);
                            quickAdapter.notifyDataSetChanged();
                        }
                    });
                }

                LinearLayout item_ll = helper.getView(R.id.item_ll);
                item_ll.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (Utils.isDoubleClick()) {
                            return;
                        }
                        if (item.getModule() == 2 || item.getModule() == 4) {
                            if (item.getContentType() == 1) {
                                Bundle bundle = new Bundle();
                                bundle.putString("id", item.getContentId() + "");
                                bundle.putString("flag", "comment");
                                startActivity(FindDetailActivity.class, bundle);
                            } else if (item.getContentType() == 2) {
                                HttpParams params1 = new HttpParams();
                                params1.put("id", item.getContentId());
                                if (mUserInfoBean != null) {
                                    params1.put("userId", mUserInfoBean.getUser().getUserId());
                                }
                                finalOkGo.request(RequestType.POST, Url.FIND_DETAIL, params1, Url.FIND_DETAIL, new Callback<FindDetailBean>() {
                                    @Override
                                    public void onSuccess(FindDetailBean findDetailBean) {
                                        if (findDetailBean.getCode() == Contacts.SUCCESS) {
                                            Bundle bundle = new Bundle();
                                            VideoListBean videoListBean = new VideoListBean();
                                            videoListBean.setVideoDownloadUrl(findDetailBean.getDiscover().getContent());
                                            videoListBean.setCoverImgUrl(findDetailBean.getDiscover().getContent() + "?vframe/jpg/offset/1");
                                            videoListBean.setTitle(findDetailBean.getDiscover().getTitle());
                                            videoListBean.setComment_num(findDetailBean.getDiscover().getCommentSum());
                                            videoListBean.setPraise_num(findDetailBean.getDiscover().getLikeSum());
                                            videoListBean.setHeadPhoto(findDetailBean.getDiscover().getAvatar());
                                            videoListBean.setNickName(findDetailBean.getDiscover().getNickname());
                                            videoListBean.setTime(findDetailBean.getDiscover().getCreateTime());
                                            videoListBean.setIsLike(findDetailBean.getDiscover().getIsLike());
                                            videoListBean.setAnonymity(0);
                                            videoListBean.setUserId(findDetailBean.getDiscover().getUserId());
                                            videoListBean.setContentId(findDetailBean.getDiscover().getId());
                                            videoListBean.setModule(2);
                                            bundle.putSerializable("data", videoListBean);
                                            bundle.putInt("videoId", findDetailBean.getDiscover().getId());
                                            bundle.putString("flag", "mineVideo");
                                            bundle.putString("categoriesId", findDetailBean.getDiscover().getCategoriesId()+"");
//                                            bundle.putInt("position", i);
                                            startActivity(FindVideoDetailActivity.class, bundle);
                                        }
                                    }
                                });

                            }
                        } else if (item.getModule() == 0 || item.getModule() == 1) {
                            if (item.getOperation() == 5) {
                                Bundle bundle1 = new Bundle();
                                bundle1.putString("id", item.getContentId() + "");
                                bundle1.putString("flag", "comment");
                                startActivity(ByIdDetailActivity.class, bundle1);
                            } else {
                                Bundle bundle1 = new Bundle();
                                bundle1.putString("id", item.getContentId() + "");
                                startActivity(ByIdDetailActivity.class, bundle1);
                            }

                        }

                        item.setStatus(1);
                        quickAdapter.notifyDataSetChanged();
                    }
                });

                item_ll.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View view) {
                        DialogUtil.getInstance().showCenterDialog(getActivity(), R.layout.dialog_message_more);
                        LinearLayout dialog_message_more = (LinearLayout) DialogUtil.getInstance().dialog_center_layout;

                        LinearLayout delete = dialog_message_more.findViewById(R.id.delete);

                        delete.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                if (Utils.isDoubleClick()) {
                                    return;
                                }
                                DialogUtil.getInstance().dialog_center.dismiss();
                                showDialog(context, "删除中...");
                                HttpParams params = new HttpParams();
                                params.put("id", item.getId());
                                finalOkGo.requestHead(RequestType.POSTHEAD, Url.DELETE_REMIND_MESSAGE, params, Url.DELETE_REMIND_MESSAGE, new Callback<SendCodeBean>() {
                                    @Override
                                    public void onSuccess(SendCodeBean sendCodeBean) {
                                        dismissDialog();
                                        if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                                            quickAdapter.remove(helper.getPosition());
                                            notifyDataSetChanged();
                                        } else {
                                            if (sendCodeBean.getCode() == Contacts.TOKEN_EMPTY) {
                                            } else {
                                                showImageToas(sendCodeBean.getMsg());
                                            }
                                        }
                                    }

                                    @Override
                                    public void onError(Response response) {
                                        super.onError(response);
                                        dismissDialog();
                                    }
                                });
                            }
                        });
                        return true;
                    }
                });
            }
        };

        listview.setAdapter(quickAdapter);

        listview.setFocusable(false);

        return view;
    }

    @Override
    protected void initData() {
        showDialog(context, null);
        HttpParams params = new HttpParams();
        params.put("operation", "4,5");
        params.put("page", pageNum++);
        params.put("limit", pageSize);
        finalOkGo.requestHead(RequestType.POSTHEAD, Url.MESSAGE_REMIND_LIST, params, Url.MESSAGE_REMIND_LIST, new Callback<MessageRemindBean>() {
            @Override
            public void onSuccess(MessageRemindBean messageRemindBean) {
                dismissDialog();
                if (messageRemindBean.getCode() == Contacts.SUCCESS) {
                    if (pageNum - 1 == 1) {
                        quickAdapter.clear();
                        quickAdapter.addAll(messageRemindBean.getPage().getList());
                    } else {
                        quickAdapter.addAll(messageRemindBean.getPage().getList());
                    }
                    refreshLayout.finishRefresh();
                    refreshLayout.finishLoadMore();
                    quickAdapter.notifyDataSetChanged();

                    int pagecount;
                    if (messageRemindBean.getPage().getTotalCount() % pageSize == 0) {
                        pagecount = messageRemindBean.getPage().getTotalCount() / pageSize;
                    } else {
                        pagecount = messageRemindBean.getPage().getTotalCount() / pageSize + 1;
                    }

                    if (pageNum > pagecount) {
                        refreshLayout.setNoMoreData(true);
                        refreshLayout.finishLoadMoreWithNoMoreData();
                    } else {
                        refreshLayout.setNoMoreData(false);
                    }
                } else {
                    refreshLayout.finishRefresh();
                    refreshLayout.finishLoadMore();
                    if (messageRemindBean.getCode() == Contacts.TOKEN_EMPTY) {
                    } else {
                        showImageToas(messageRemindBean.getMsg());
                    }
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                dismissDialog();
                if (refreshLayout != null) {
                    refreshLayout.finishRefresh();
                    refreshLayout.finishLoadMore();
                }
            }
        });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
    }


    //    @Override
    @OnClick({R.id.mark_read, R.id.praise, R.id.comment, R.id.follow})
    public void onViewClicked(View view) {
//        super.onViewClicked(view);
        if (Utils.isDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.mark_read:
                showDialog(context, "读取中...");
                finalOkGo.requestHead(RequestType.POSTHEAD, Url.CLEAR_MESSAGE_REMIND, null, Url.CLEAR_MESSAGE_REMIND, new Callback<SendCodeBean>() {
                    @Override
                    public void onSuccess(SendCodeBean sendCodeBean) {
                        dismissDialog();
                        if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                            EventBus.getDefault().post("clearMessageRemind");
                        } else {
                            if (sendCodeBean.getCode() == Contacts.TOKEN_EMPTY) {
                            } else {
                                showImageToas(sendCodeBean.getMsg());
                            }
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        dismissDialog();
                    }
                });
                break;
            case R.id.praise:
                Bundle bundle = new Bundle();
                bundle.putInt("operation", 2);
                startActivity(PraiseCommentFollowActivity.class, bundle);
                MobclickAgent.onEvent(ContextUtil.getContext(), "praiseMyID");
                break;
            case R.id.comment:
                Bundle bundle1 = new Bundle();
                bundle1.putInt("operation", 3);
                startActivity(PraiseCommentFollowActivity.class, bundle1);
                MobclickAgent.onEvent(ContextUtil.getContext(), "commentMyID");
                break;
            case R.id.follow:
                Bundle bundle2 = new Bundle();
                bundle2.putInt("operation", 1);
                startActivity(PraiseCommentFollowActivity.class, bundle2);
                MobclickAgent.onEvent(ContextUtil.getContext(), "newFocusID");
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void OnMessageEvent(String event) {
        if (event.contains("remindCount")) {
            String[] remindCount = event.split(":");
            if (Integer.parseInt(remindCount[1]) != 0) {
                praiseNum.setVisibility(View.VISIBLE);
                praiseNum.setText(remindCount[1]);
            } else {
                praiseNum.setVisibility(View.GONE);
            }

            if (Integer.parseInt(remindCount[2]) != 0) {
                commentNum.setVisibility(View.VISIBLE);
                commentNum.setText(remindCount[2]);
            } else {
                commentNum.setVisibility(View.GONE);
            }

            if (Integer.parseInt(remindCount[3]) != 0) {
                followNum.setVisibility(View.VISIBLE);
                followNum.setText(remindCount[3]);
            } else {
                followNum.setVisibility(View.GONE);
            }

            if ((Integer.parseInt(remindCount[1]) + Integer.parseInt(remindCount[2]) + Integer.parseInt(remindCount[3])) > 5) {
                markLl.setVisibility(View.VISIBLE);
            } else {
                markLl.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        initData();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        EventBus.getDefault().post("clearMessageRemind");
//        refreshLayout.finishRefresh();
        pageNum = 1;
        initData();
    }
}
